package com.example.medicalzb.service;

import com.example.medicalzb.domain.City;
import com.example.medicalzb.entity.CityEntity;
import com.example.medicalzb.mapper.CityMapper;
import com.example.medicalzb.mapper.MedicalPolicyMapper;
import com.example.medicalzb.model.CityModel;
import com.example.medicalzb.util.Msg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CityService {
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private MedicalPolicyMapper medicalPolicyMapper;
    public PageInfo<CityModel> getCityWithPage(Integer pn, Integer size, String name) {
        if (pn == null){
            pn = 1;
        }
        if (size == null){
            size =0;
        }
        PageHelper.startPage(pn,size);
        List<CityModel> list = cityMapper.getAllCity(name);
        PageInfo<CityModel> pageInfo = new PageInfo<>(list,5);
        return pageInfo;
    }

    public Msg getCityById(Integer id) {
        City city = cityMapper.getCityById(id);
        if (city != null){
            return Msg.success().data("city", city);
        }
        return Msg.fail().mess("未找到城市");
    }

    public Integer checkCityByNumber(Integer cityNumber) {
        return cityMapper.checkCityByNumber(cityNumber);
    }

    public Msg saveCity(Integer cityNumber) {
        CityEntity cityEntity = new CityEntity();
        cityEntity.setCreatetime(new DateTime().toDate());
        cityEntity.setUpdatetime(new DateTime().toDate());
        cityEntity.setCityNumber(cityNumber);
        int i = cityMapper.saveCity(cityEntity);
        if (i > 0){
            Long num = cityEntity.getTotal() % 5 == 0 ? (cityEntity.getTotal() / 5) : ((cityEntity.getTotal() / 5) + 1);
            return Msg.success().data("pages",num).mess("添加成功");
        }
        return Msg.fail().mess("添加失败");
    }

    public Msg deleteCityById(Integer id) {
        int i = cityMapper.deleteCityById(id);
        medicalPolicyMapper.deleteByCity(id);
        if (i > 0){
            return Msg.success().mess("删除成功");
        }else {
            return Msg.fail().mess("删除失败");
        }

    }
}
